<?php

namespace app\api\controller;

use support\Request;
use Tinywan\Jwt\JwtToken;
use EasyWeChat\Factory;
use app\model\User;

class AuthController
{
    /**
     * easywechat 5.0 SDK
     */
    public $app;

    public function __construct()
    {
        $config = config('wechat');

        $this->app = Factory::miniProgram($config);
    }
    /**
     * 获取微信小程序手机号
     * @params string
     * @return
     */
    public function getWechatPhone(Request $request)
    {
        $code = $request->post('code');
        try {
            $result = $this->app->phone_number->getUserPhoneNumber($code);
            if($result['errcode'] == 0 && $result['errmsg'] == 'ok')
            {
                $res['phone'] = $result['phone_info']['phoneNumber'];
                return returnSuccess('ok', $res);
            }else{
                return returnFail('获取手机号失败');
            }
        }catch (\Exception $e)
        {
            return returnFail('获取手机号失败');
        }
    }

    /**
     * 微信小程序登录
     * @params string
     * @return
     */
    public function mpLogin(Request $request)
    {
        $js_code  = $request->post('js_code');
        $phone    = $request->post('phone');
        if(empty($phone) || !preg_match("/^1[3456789]{1}\d{9}$/",$phone))
        {
            return returnFail('手机号不正确');
        }
        if(empty($js_code))
        {
            return returnFail('缺少js_code');
        }
        $res = $this->app->auth->session($js_code);
        if(!isset($res['openid']) || empty($res['openid']))
        {
            return returnFail('获取openid失败');
        }
        $openid = $res['openid'];
        $user_info = User::getUserInfo(['openid'=>$openid], 'id,username,openid,phone');
        if(empty($user_info))
        {
            //注册
            $reg['username'] = '用户_'.get_random_str(4);
            $reg['avatar']   = getUploadLocalDomain().'/common/default_avatar.jpeg';
            $reg['phone']    = $phone;
            $reg['sex']      = '男';
            $reg['openid']   = $openid;

            $reg_res = User::create($reg);
            $reg['id'] = $reg_res->id;

            $token = JwtToken::generateToken($reg);
        }else{
            $token = JwtToken::generateToken($user_info);
        }

        return returnSuccess('ok', ['token'=>$token]);
    }

}
